<template>
  <i :class="svgClass" :style="style" v-if="isExternal" />
  <svg v-else :class="svgClass" :style="style" aria-hidden="true">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script setup lang="ts">
import { computed } from 'vue'

interface Props {
  iconClass?: string
  className?: string
  color?: string
  size?: string | number
}

const props = withDefaults(defineProps<Props>(), {
  iconClass: '',
  className: '',
  color: '',
  size: ''
})

const isExternal = computed(() => {
  return props.iconClass && /^https?:\/\//.test(props.iconClass)
})

const iconName = computed(() => {
  return `#icon-${props.iconClass}`
})

const svgClass = computed(() => {
  if (props.className) {
    return `svg-icon ${props.className}`
  } else {
    return 'svg-icon'
  }
})

const style = computed(() => {
  const styles: Record<string, string> = {}
  if (props.color) {
    styles.color = props.color
  }
  if (props.size) {
    styles.fontSize = typeof props.size === 'number' ? `${props.size}px` : props.size
  }
  return styles
})
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>